package com.spzx.product.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.utils.bean.BeanUtils;
import com.spzx.product.domain.Category;
import com.spzx.product.domain.vo.CategoryExcelVo;
import com.spzx.product.mapper.CategoryMapper;
import com.spzx.product.service.ICategoryService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Autowired
    private CategoryMapper categoryMapper;
    @Override
    public List<Category> treeSelect(Long parentId) {
        List<Category> list = categoryMapper.selectList(new LambdaQueryWrapper<Category>().eq(Category::getParentId, parentId));
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(item -> {
                long count = categoryMapper.selectCount(new LambdaQueryWrapper<Category>().eq(Category::getParentId, item.getId()));
                if (count > 0) {
                    item.setHasChildren(true);
                } else {
                    item.setHasChildren(false);
                }
            });
        }
        return list;
    }

    @Override
    public List<Long> getAllCategoryIdList(Long id) {
        List<Long> list = new ArrayList<>();
        List<Category> categoryList = getParentCategory(id, new ArrayList<Category>());
        int size = categoryList.size();
        for (int i = size-1 ; i >= 0; i--) {
            list.add(categoryList.get(i).getId());
        }
        return list;
    }

    @Override
    public void exportData(HttpServletResponse response) {
        try {
            // 设置响应结果类型
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");

            String fileName = URLEncoder.encode("分类数据.xls", "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");

            List<Category> categoryList = categoryMapper.selectList(null);
            List<CategoryExcelVo> categoryExcelVoList = new ArrayList<>(categoryList.size());

            for (Category category : categoryList) {
                CategoryExcelVo categoryExcelVo = new CategoryExcelVo();
                BeanUtils.copyProperties(category, categoryExcelVo, CategoryExcelVo.class);
                categoryExcelVoList.add(categoryExcelVo);
            }

            EasyExcel.write(response.getOutputStream(), CategoryExcelVo.class).sheet( "分类数据").doWrite(categoryExcelVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void importData(MultipartFile file) {
        //使用EasyExcel读取文件
        try {
            List<CategoryExcelVo> categoryExcelVoList = EasyExcel
                    .read(file.getInputStream())
                    .head(CategoryExcelVo.class)
                    .sheet()
                    .doReadSync();
            if (!CollectionUtils.isEmpty(categoryExcelVoList)) {
                List<Category> categoryList = new ArrayList<>(categoryExcelVoList.size());
                for (CategoryExcelVo categoryExcelVo : categoryExcelVoList) {
                    Category category = new Category();
                    BeanUtils.copyProperties(categoryExcelVo, category, Category.class);
                    categoryList.add(category);
                }
                this.saveBatch(categoryList);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private List<Category> getParentCategory(Long id,List<Category> categoryList) {
        while (id > 0) {
            Category category = categoryMapper.selectOne(new LambdaQueryWrapper<Category>().eq(Category::getId, id).select(Category::getId, Category::getParentId));
            categoryList.add(category);
            return getParentCategory(category.getParentId(), categoryList);
        }
        return categoryList;
    }
}
